<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from "vue";
import { ElMessage, ElLoading } from "element-plus";

defineOptions({
  name: "Document"
});

const props = defineProps({
  url: {
    type: String,
    required: true
  }
});

const documentUrl = ref<string>("");
const documentType = ref<"pdf" | "word" | "unknown">("unknown");
const pdfContainer = ref<HTMLDivElement>();
const wordContent = ref<string>("");
const loading = ref(false);

const getDocumentUrl = () => {
  if (!props.url) {
    console.log("props.url", props.url);
    ElMessage.error("未提供文档URL");
    return;
  }
  documentUrl.value = props.url;
  detectDocumentType(props.url);
};

// 检测文档类型
const detectDocumentType = (url: string) => {
  const urlObj = new URL(url);
  const fullUrl = urlObj.origin + urlObj.pathname;

  const extension = fullUrl.split(".").pop();

  if (extension === "pdf") {
    documentType.value = "pdf";
  } else if (["doc", "docx"].includes(extension || "")) {
    documentType.value = "word";
  } else {
    documentType.value = "unknown";
    ElMessage.warning("不支持的文档类型，仅支持 PDF 和 Word 文档");
  }
};

// 加载PDF文档
const loadPDF = async () => {
  if (!documentUrl.value || !pdfContainer.value) {
    return;
  }

  loading.value = true;
  const loadingInstance = ElLoading.service({
    target: pdfContainer.value,
    text: "正在加载PDF文档..."
  });

  try {
    // 动态导入 pdfjs-dist
    const pdfjsLib = await import("pdfjs-dist");

    // 设置 worker - 使用本地 worker 或匹配版本
    // 使用本地 worker 文件，避免 CORS 问题
    pdfjsLib.GlobalWorkerOptions.workerSrc = "./pdf.worker.min.js";

    const pdf = await pdfjsLib.getDocument(documentUrl.value).promise;

    // 清空容器
    pdfContainer.value.innerHTML = "";

    // 渲染所有页面
    for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
      const page = await pdf.getPage(pageNum);
      const scale = 1.5;
      const viewport = page.getViewport({ scale });

      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      if (!context) {
        console.error("无法获取canvas context");
        continue;
      }

      canvas.height = viewport.height;
      canvas.width = viewport.width;
      canvas.style.marginBottom = "10px";
      canvas.style.border = "1px solid #ddd";

      pdfContainer.value.appendChild(canvas);

      const renderContext = {
        canvasContext: context,
        viewport: viewport,
        canvas: canvas
      };

      await page.render(renderContext).promise;
    }
  } catch (error) {
    console.error("PDF加载失败:", error);
    ElMessage.error("PDF文档加载失败");
  } finally {
    loading.value = false;
    loadingInstance.close();
  }
};

// 加载Word文档
const loadWord = async () => {
  if (!documentUrl.value) return;

  loading.value = true;
  const loadingInstance = ElLoading.service({
    text: "正在加载Word文档..."
  });

  try {
    // 获取文档数据
    const response = await fetch(documentUrl.value);
    if (!response.ok) {
      throw new Error("文档获取失败");
    }

    const arrayBuffer = await response.arrayBuffer();

    // 动态导入 mammoth
    const mammoth = await import("mammoth");

    // 转换为HTML
    const result = await mammoth.convertToHtml({ arrayBuffer });
    wordContent.value = result.value;

    if (result.messages.length > 0) {
      console.warn("Word转换警告:", result.messages);
    }
  } catch (error) {
    console.error("Word文档加载失败:", error);
    ElMessage.error("Word文档加载失败");
  } finally {
    loading.value = false;
    loadingInstance.close();
  }
};

// 加载文档
const loadDocument = () => {
  if (documentType.value === "pdf") {
    loadPDF();
  } else if (documentType.value === "word") {
    loadWord();
  }
};

// 监听文档类型变化，确保在 DOM 渲染完成后加载文档
watch(documentType, async newType => {
  if (newType !== "unknown" && documentUrl.value) {
    await nextTick(); // 确保 DOM 更新完成
    loadDocument();
  }
});

onMounted(() => {
  getDocumentUrl();
});
</script>

<template>
  <div v-loading="loading" class="document-content">
    <!-- PDF预览容器 -->
    <div
      v-if="documentType === 'pdf'"
      ref="pdfContainer"
      class="pdf-container"
    />

    <!-- Word预览容器 -->
    <div
      v-else-if="documentType === 'word'"
      class="word-container"
      v-html="wordContent"
    />

    <!-- 不支持的文档类型 -->
    <div v-else class="unsupported-type">
      <el-empty description="不支持的文档类型">
        <template #image>
          <svg viewBox="0 0 1024 1024" width="64" height="64">
            <path
              d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"
              fill="#faad14"
            />
            <path
              d="M464 688a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm24-112h48c4.4 0 8-3.6 8-8V296c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v272c0 4.4 3.6 8 8 8z"
              fill="#faad14"
            />
          </svg>
        </template>
        <p>仅支持 PDF 和 Word 文档预览</p>
      </el-empty>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.document-content {
  flex: 1;
  overflow: auto;
  padding: 24px;

  .pdf-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;

    .pdf-page-info {
      background: #f0f9ff;
      color: #1890ff;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
    }

    .pdf-page-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;

      .pdf-page-label {
        background: #fafafa;
        color: #666;
        padding: 4px 12px;
        border-radius: 4px;
        font-size: 12px;
      }

      .pdf-page-canvas {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        border-radius: 4px;
        border: 1px solid #e8e8e8;
      }
    }

    .error-message {
      text-align: center;
      padding: 40px;
      color: #666;

      h3 {
        color: #f56565;
        margin-bottom: 16px;
      }

      ul {
        text-align: left;
        margin: 16px 0;

        li {
          margin: 8px 0;
        }
      }
    }

    canvas {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      border-radius: 4px;
    }
  }

  .word-container {
    background: white;
    padding: 40px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    max-width: 800px;
    margin: 0 auto;
    line-height: 1.6;

    :deep(h1),
    :deep(h2),
    :deep(h3),
    :deep(h4),
    :deep(h5),
    :deep(h6) {
      color: #333;
      margin: 20px 0 10px 0;
    }

    :deep(p) {
      margin: 10px 0;
      color: #555;
    }

    :deep(table) {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;

      th,
      td {
        border: 1px solid #ddd;
        padding: 8px 12px;
        text-align: left;
      }

      th {
        background: #f5f5f5;
        font-weight: 600;
      }
    }

    :deep(img) {
      max-width: 100%;
      height: auto;
      margin: 10px 0;
    }
  }

  .unsupported-type {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
  }
}
</style>
